<?php
/**
 * BowlFramework Files
 * 
 * 这家伙太懒了，连注释都不写，鄙视他
 * 
 * @author armor
 * @date 13-7-11 下午6:22
 * 
 */

class Controller_Package extends Extension_Controller_FenderEngineBase{

    /**
     * 安装应用引擎
     * 1） 拷贝程序代码
     * 2）如有数据库，则创建数据文件
     * 3）需要生成一个友好的首页，应用首页里需要有返回到站点首页的链接
     * 4）完成后需要返回BOOL型结果
     *
     * @return bool
     */
    public function install(){
        $this->installProgramFiles($this->appPreviewDir);
        $this->installDB($this->appPreviewDir);

        $this->view->assign('app',$this->app);
        $html = $this->view->asHtml($this->appEngineViewDir."/boxtpl/index.php");
        Service_PortalWriter::writeFile($this->appPreviewDir."/index.php",$html);

        $content='<?php $appId='.$this->app['app_id'].';';
        Service_PortalWriter::writeFile($this->appPreviewDir."/app.php",$content,true);
        return true;
    }


    /**
     * 应用引擎升级
     *
     * @param $oldVersion
     */
    public function upgrade($oldVersion){
        $hasMac = $this->activeDb()->query("DESCRIBE appengine_advice_contents advice_mac")->run();
        if($hasMac == 0){
            $addMac = $this->activeDb()->query("ALTER TABLE  `appengine_advice_contents` ADD advice_mac VARCHAR(100) NULL")->run();
        }

        $db =new SQLite3($this->appPreviewDir."/advice.mimao");
        $sql = 'SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "advice_contents"';
        $res= $db->query($sql);
        $res = $res->fetchArray(SQLITE3_NUM);
        $isExists = stripos($res['1'],'advice_mac');
        if($isExists === false){
            $addSql = 'ALTER TABLE advice_contents ADD advice_mac varchar(100)';
            $addRes = $db->query($addSql);
        }

        $this->installProgramFiles($this->appPreviewDir);
        $content='<?php $appId='.$this->app['app_id'].';';
        Service_PortalWriter::writeFile($this->appPreviewDir."/app.php",$content,true);

        $this->view->assign('app',$this->app);
        $html = $this->view->asHtml($this->appEngineViewDir."/boxtpl/index.php");
        Service_PortalWriter::writeFile($this->appPreviewDir."/index.php",$html);
    }

    /**
     * 卸载应用
     * 在这里完成应用的卸载，目录的清除已由系统完成，应用引擎自己只需要完成数据库的清理
     */
    public function uninstall(){

    }

    /**
     * 安装数据表数据
     *
     * @param $destPath
     */
    private function installDB($destPath){
        $tableSqlArray = array(
            "create table advice_contents (
              advice_id varchar(32) primary key,
              advice_content nvarchar(2000) ,
              advice_mac varchar(100),
              createtime varchar(14)
            )",
        );
        $dbFileName = $destPath."/advice.mimao";
        $db = new SQLite3($dbFileName);
        foreach($tableSqlArray as $table){
            if(false !== $db->exec($table)){}
        }
        Service_PortalWriter::addFile2SVN($dbFileName);
    }

    /**
     * 安装程序文件
     *
     * @param $destPath
     */
    private function installProgramFiles($destPath){
        $boxAppPackDir = $this->appEngineBaseDir."/BoxAppPack/";
        Service_PortalWriter::copyDirectory($boxAppPackDir,$destPath);
    }
    public function fileSync($path,$mac){
        $pathInfo=pathinfo($path);
        $dbName=$pathInfo['basename'];
        $appId=$pathInfo['extension'];
        if($path === false || $dbName === false || $appId === false){
            $this->response->ajaxJson(false,'参数无效');
        }

        $sqlitedb = new SQLite3($path);
        if($sqlitedb === false){
            throw new Exception('db content fail');
            exit;
        }
        $sql=array();
        $sql['sel']='select * from advice_contents order by createtime desc';
        $rs1 = $sqlitedb->query($sql['sel']);
        while($row = $rs1->fetchArray(SQLITE3_ASSOC)){
            $count=$this->appModel("Content")->isexist($row['advice_id']);
            if($count == 0){
                $insert=array(
                    'advice_id'=>$row['advice_id'],
                    'advice_content'=>$row['advice_content'],
                    'createtime'=>date("Y-m-d"),
                    'app_id'=>$this->app['app_id']
                );
                $res=$this->appModel("Content")->create($insert);
                if($res === false){
                    throw new Exception('insert fail=>'.$row['advice_id']);
                }
            }
        }


    }
}